package com.yc.system.consumer;

import com.yc.common.constant.Constant;
import com.yc.common.constant.RabbitMQConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component("emailCodeConsumer")
public class EmailCodeConsumer {

    private static final Logger logger = LoggerFactory.getLogger(EmailCodeConsumer.class);

    @Value("${spring.mail.username}")
    private String fromEmail;

    private final JavaMailSender mailSender;

    public EmailCodeConsumer(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    @RabbitListener(queues = RabbitMQConstant.EMAIL.EMAIL_CODE_QUEUE)
    @RabbitHandler
    public void handleEmailCode(Map<String, String> message) {
        String email = message.get("email");
        String code = message.get("code");

        try {
            sendEmailWithRetry(email, code);
        } catch (Exception e) {
            logger.error("发送邮件失败: {}", e.getMessage(), e);
            // 这里可以添加告警通知
        }
    }

    @Retryable(
            value = Exception.class,
            maxAttempts = 3,
            backoff = @Backoff(delay = 1000, multiplier = 2)
    )
    public void sendEmailWithRetry(String email, String code) {
        sendEmail(email, code);
    }

    private void sendEmail(String email, String code) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(fromEmail);
        mailMessage.setTo(email);
        mailMessage.setSubject(Constant.Captcha.EMAIL_SUBJECT);
        mailMessage.setText(String.format(
                Constant.Captcha.EMAIL_CONTENT_TEMPLATE,
                code,
                Constant.Captcha.CODE_EXPIRE_MINUTES
        ));

        mailSender.send(mailMessage);
        logger.info("验证码邮件发送成功: {}", email);
    }
}
